const apiWfScheme = window.$api.workflow.scheme;
const apiWfProcess = window.$api.workflow.process;

import mixin from "./form";
export default function () {
  return {
    mixins: [mixin()],
    created() {},
    props: {
      visible: {
        type: Boolean,
      },
      title: String,
      code: String,
      isLoadFormData: Boolean,
      params: {
        type: Object,
        default: () => {
          return {};
        },
      },
      type: String,

      isToken: false,
    },
    data() {
      return {
        // 流程信息
        wfscheme: {},
        wfData: [],
        currentNode: {},
        processId: "",
        taskId: "",
        task: null,
        process: null,
        logs: [], // 流程日志信息
        nodeMap: {}, // 需要处理的任务
        userLogs: [], // 人员日志信息
        nodeLogs: [],
        taskBtns: [],

        activeName: "form",
      };
    },
    computed: {
      hasForm() {
        return this.isForm(this.currentNode);
      },
    },
    methods: {
      async handleOpened(showLoading, hideLoading) {
        showLoading("加载流程信息...");
        await this.loadWf();
        hideLoading();
      },
      handleClosed() {
        this.$emit("update:visible", false);
        this.activeName = "form";

        this.resetWfForm && this.resetWfForm();
        this.resetFormToMe && this.resetFormToMe();
      },
      async loadWf() {
        // 加载流程信息
        let data = null;
        switch (this.type) {
          case "audit":
          case "look":
            this.taskId = this.params.taskId;
            if (!this.isToken) {
              data = await this.$awaitWraper(apiWfProcess.getTask(this.params.taskId));
            } else {
              data = await this.$awaitWraper(apiWfProcess.GetTaskByToken(this.params.taskId));
              if (data == null) {
                this.midVisible = false;
                return;
              }
              this.taskId = data.task.f_Id;
            }

            this.process = data.process;
            this.task = data.task;
            this.processId = this.process.f_Id;

            this.setLogsAndTasks(data.logs || [], data.tasks);
            break;
          case "lookmy":
            this.processId = this.params.processId;
            data = await this.$awaitWraper(apiWfProcess.get(this.params.processId));
            this.process = data.process;
            this.setLogsAndTasks(data.logs || [], data.tasks);
            break;
          case "draft":
            this.processId = this.params.processId;
            data = await this.$awaitWraper(apiWfProcess.getDraft(this.params.processId));
            this.process = data.process;
            break;
          default: // 去掉 wf_
            this.processId = `${this.$uuid()}`;
            data = await this.$awaitWraper(apiWfScheme.get(this.code));
            break;
        }

        if (data) {
          const { scheme } = data;
          this.wfscheme = JSON.parse(scheme.f_Content);
          const { wfData } = this.wfscheme;
          wfData.forEach((item) => {
            const node = this.nodeMap[item.id];
            if (node && item.strokeColor == undefined) {
              if (node.find((t) => !t.isFinish)) {
                item.strokeColor = "#409EFF";
              } else {
                item.strokeColor = "#67C23A";
              }

              if (node.find((t) => t.isFinish)) {
                item.hasFinish = true;
              }
            }
          });
          this.wfData = wfData;
          this.setForm && this.setForm(data);

          const startNode = this.wfData.find((t) => t.type == "startEvent");
          if (!startNode.name) {
            startNode.name = "开始节点";
          }

          if (this.currentNode.isInherit) {
            // 如果是继承表单就开始节点的表单信息

            this.currentNode.formType = startNode.formType;
            this.currentNode.formVerison = startNode.formVerison;
            this.currentNode.formRelationId = startNode.formRelationId;
            this.currentNode.formUrl = startNode.formUrl;
            this.currentNode.authFields = startNode.authFields;
          }

          if (this.hasForm) {
            await this.loadForm(
              this.currentNode,
              this.processId,
              this.params,
              this.isLoadFormData,
              ["look", "lookmy"].includes(this.type)
            );

            if (this.hasWfForm == false) {
              this.activeName = "wfinfo";
              this.handleTabClick();
            }
          } else {
            this.activeName = "wfinfo";
            this.handleTabClick();
          }
        } else {
          this.$message({
            type: "error",
            message: "流程加载失败!",
          });
        }
      },
      setLogsAndTasks(logs, tasks) {
        const res = [];
        const taskMap = {};
        const nodeMap = {};
        const userLogs = [];

        tasks.forEach((task) => {
          nodeMap[task.f_UnitId] = nodeMap[task.f_UnitId] || [
            {
              unitId: task.f_UnitId,
              name: task.f_UnitName,
              userIds: [],
              des: "正在审核",
              time: `当前-创建时间:${this.lr_dateFormat(task.f_CreateDate)}`,
              type: "primary",
              isFinish: false,
            },
          ];

          if (task.f_Type == 2) {
            taskMap[task.f_UnitId + task.f_Type] = taskMap[task.f_UnitId + task.f_Type] || {
              unitId: task.f_UnitId,
              name: task.f_UnitName,
              userIds: [],
              des: "正在查阅",
              time: `当前-创建时间:${this.lr_dateFormat(task.f_CreateDate)}`,
              type: "primary",
            };
            taskMap[task.f_UnitId + task.f_Type].userIds.push(task.f_UserId);

            if (nodeMap[task.f_UnitId].length == 1) {
              nodeMap[task.f_UnitId].push({
                unitId: task.f_UnitId,
                name: task.f_UnitName,
                userIds: [],
                des: "正在查阅",
                time: `当前-创建时间:${this.lr_dateFormat(task.f_CreateDate)}`,
                type: "primary",
                isFinish: true,
              });
            }
            nodeMap[task.f_UnitId][1].userIds.push(task.f_UserId);
          } else {
            taskMap[task.f_UnitId] = taskMap[task.f_UnitId] || {
              unitId: task.f_UnitId,
              name: task.f_UnitName,
              userIds: [],
              des: "正在审核",
              time: `当前-创建时间:${this.lr_dateFormat(task.f_CreateDate)}`,
              type: "primary",
            };
            taskMap[task.f_UnitId].userIds.push(task.f_UserId);
            nodeMap[task.f_UnitId][0].userIds.push(task.f_UserId);
          }
        });

        for (let key in taskMap) {
          res.push(taskMap[key]);
        }

        for (let key in nodeMap) {
          nodeMap[key] = nodeMap[key].filter((t) => t.userIds.length > 0);
        }

        logs.forEach((log) => {
          res.push({
            unitId: log.f_UnitId,
            name: log.f_UnitName,
            userIds: [log.f_UserId],
            des: log.f_Des ? log.f_Des : log.f_OperationName,
            time: this.lr_dateFormat(log.f_CreateDate),
            type: "info",
          });

          nodeMap[log.f_UnitId] = nodeMap[log.f_UnitId] || [];
          nodeMap[log.f_UnitId].push({
            unitId: log.f_UnitId,
            name: log.f_UnitName,
            userIds: [log.f_UserId],
            time: this.lr_dateFormat(log.f_CreateDate),
            des: log.f_Des ? log.f_Des : log.f_OperationName,
            type: "info",
            isFinish: true,
          });

          if (log.f_TaskType == 1 && !["sign"].includes(log.f_OperationCode)) {
            // 右侧显示审核记录
            const userLogIndex = userLogs.findIndex((t) => t.id == log.f_UnitId);
            if (userLogIndex == -1) {
              userLogs.push({
                id: log.f_UnitId,
                name: log.f_UnitName,
                user: log.f_UserName,
                time: this.lr_dateFormat(log.f_CreateDate),
                des: log.f_Des,
                img: log.f_StampImg,
              });
            }
          }
        });

        this.logs = res;
        this.nodeMap = nodeMap;
        this.userLogs = userLogs.sort(function (a, b) {
          return b.time < a.time ? -1 : 1;
        });

        //console.log(logs,'logs')
      },

      handleTabClick() {
        if (this.activeName == "wfinfo") {
          this.$nextTick(() => {
            this.$refs.bflow.setData(this.$deepClone(this.wfData));
          });
        }
      },

      isForm(node) {
        if (node.isInherit) {
          node = this.wfData.find((t) => t.type == "startEvent");
        }

        const { formType, formVerison, formUrl } = node;
        if (formType == "1") {
          if (!formVerison) {
            return false;
          }
        } else {
          if (!formUrl) {
            return false;
          }
        }
        return true;
      },
      isFormById(id) {
        const node = this.wfData.find((t) => t.id == id);
        if (node) {
          return this.isForm(node);
        } else {
          return false;
        }
      },
    },
  };
}
